﻿using System;
using System.Data.SqlClient;
using Devv.Core.UniDataTier;
using Yglu.BusinessLayer.Entities;

namespace Yglu.BusinessLayer
{
	public partial class DataAccess
	{
		#region Get

		public static SqlDataReader User_Get()
		{
			DataHandler db = new DataHandler();

			return (SqlDataReader)db.ExecuteReader("upUser_Get");
		}

		public static SqlDataReader User_Get(Int32 id)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@UserId", id);

			return (SqlDataReader)db.ExecuteReader("upUser_Get");
		}

		public static SqlDataReader User_Get(Int32 id, String password)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@UserId", id);
			db.AddParameter("@PasswordHash", User.GetPasswordHash(id, password));

			return (SqlDataReader)db.ExecuteReader("upUser_Get");
		}

		public static SqlDataReader User_Get(Store store)
		{
			DataHandler db = new DataHandler();

			if (store != null && store.Id > 0)
			{
				db.AddParameter("@StoreId", store.Id);
			}
            
			return (SqlDataReader)db.ExecuteReader("upUser_Get");
		}

		#endregion

		#region Insert and update

		public static void User_Upsert(User user)
		{
			using (DataHandler db = new DataHandler())
			{
				db.AddParameter("@StoreId", user.Store.Id);
				db.AddParameter("@FullName", user.FullName);
				db.AddParameter("@Phone", user.Phone);
				db.AddParameter("@AdminLevel", user.AdminLevel);
				db.AddParameter("@Active", user.Active);

				if (!String.IsNullOrEmpty(user.PasswordHash))
				{
					db.AddParameter("@PasswordHash", user.PasswordHash);
				}

				if (user.Id > 0)
				{
					db.AddParameter("@UserId", user.Id);
					db.ExecuteScalar("upUser_Update");
				}
				else
				{
					user.Id = Convert.ToInt32(db.ExecuteScalar("upUser_Insert"));
				}
			}
		}

		#endregion
	}
}